#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = '霍格沃兹测试开发学社-蚊子'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""

import os

from csr_utils import log, get_root_dir
from git.repo import Repo
from git.repo.fun import is_git_dir

from commons.error_code import FileOrDirDealError


class GitUtils:

    def __init__(self, local_path, repo_url, branch='main', username=None, password=None):
        if any([not username, not password]):
            self.repo_url = repo_url
        else:
            self.repo_url = repo_url.replace("://", f"://{username}:{password}@")
        self.local_path = local_path
        self.branch = branch
        self.repo_url = repo_url
        self.repo = None
        self.is_last = self.initial(repo_url, branch)

    def initial(self, repo_url, branch):
        """
        初始化git仓库
        :param repo_url:
        :param branch:
        :return:
        """
        flag = False
        log.info(f"使用repo_url： {repo_url} | branch： {branch} 进行git初始化操作")
        if not os.path.exists(self.local_path):
            log.info(f"{self.local_path} 不存在，创建目录")
            os.makedirs(self.local_path)

        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            if len(os.listdir(self.local_path)) > 0:
                raise FileOrDirDealError("请确该文件夹为空属于git文件夹，即空文件夹或者包含.git的文件夹！")
            log.info(f"{self.local_path} 不是git目录，clone代码！")
            self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)
            flag = True
        else:
            log.info(f"{self.local_path} 已经是git目录，跳过clone代码过程！")
            self.repo = Repo(self.local_path)
        return flag

    def pull(self):
        """
        从线上拉最新代码
        :return:
        """
        log.info("进行代码拉取操作.")
        self.repo.git.pull()

    def branches(self):
        """
        获取所有分支
        :return:
        """
        branches = self.repo.remote().refs
        return_datas = [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]
        log.debug(f"获取branch列表：{return_datas}")
        return return_datas

    def commits(self):
        """
        获取所有提交记录
        :return:
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return_datas = [eval(item) for item in log_list]
        log.debug(f"获取提交记录列表：{return_datas}")
        return return_datas

    def tags(self):
        """
        获取所有tag
        :return:
        """
        return_datas = [tag.name for tag in self.repo.tags]
        log.debug(f"获取tags列表：{return_datas}")
        return return_datas

    def change_to_branch(self, branch):
        """
        切换分值
        :param branch:
        :return:
        """
        log.info(f"使用branch：{branch}进行分支切换操作.")
        self.repo.git.checkout(branch)

    def change_to_commit(self, commit, branch=None):
        """
        切换commit
        :param branch:
        :param commit:
        :return:
        """
        if not branch:
            log.info(f"未指定branch，使用默认branch：{self.branch}")
            branch = self.branch
        log.info(f"使用branch：{branch} | commit：{commit} 进行切换commit操作.")
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切换tag
        :param tag:
        :return:
        """
        log.info(f"使用tag：{tag} 进行切换tag操作.")
        self.repo.git.checkout(tag)


if __name__ == '__main__':
    gitpath = os.sep.join([get_root_dir(), "cus_workspace1"])
    git_url = "https://gitlab.ceshiren.com/ceba/tech/testplantform-group/demo_project_code.git"
    gu = GitUtils(gitpath, git_url, "ytq", "robot", "hogwarts123")
    if not gu.is_last:
        gu.pull()
    gu.commits()
